package com.adream.scalpel.app.server.service;

import com.adream.scalpel.app.client.service.UserState;
import com.adream.scalpel.app.server.domain.LoginEvent;
import com.adream.scalpel.common.server.domain.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import org.gwtwidgets.server.spring.ServletUtils;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class UserStateImpl extends RemoteServiceServlet implements UserState {
    private PersistenceManagerFactory pmf;

    public String getUserName() {
        String username = "";
        HttpSession httpSession = ServletUtils.getRequest().getSession();
        username = (String) httpSession.getAttribute("SPRING_SECURITY_LAST_USERNAME");
        PersistenceManager pm = pmf.getPersistenceManager();

        try {

            User user = pm.getObjectById(User.class, username);
            LoginEvent loginEvent = new LoginEvent(username);
            pm.makePersistent(loginEvent);
            return user.getDisplayName();
        } finally {
            pm.close();
        }
    }

    public void setPmf(PersistenceManagerFactory pmf) {
        this.pmf = pmf;
    }
}
